package com.hx.haowumall.haowumallseckill.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.hx.common.to.mq.SeckillOrderTo;
import com.hx.common.utils.R;
import com.hx.common.vo.MemberRespVo;
import com.hx.haowumall.haowumallseckill.feign.CouponFeignService;
import com.hx.haowumall.haowumallseckill.feign.ProductFeiginService;
import com.hx.haowumall.haowumallseckill.interceptor.LoginUserInterceptor;
import com.hx.haowumall.haowumallseckill.service.SeckillService;
import com.hx.haowumall.haowumallseckill.to.SeckillSkuRedisTo;
import com.hx.haowumall.haowumallseckill.vo.SeckillSessionsWithSkus;
import com.hx.haowumall.haowumallseckill.vo.SeckillSkuVo;
import com.hx.haowumall.haowumallseckill.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeiginService productFeiginService;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    RabbitTemplate rabbitTemplate;

    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";
    private final String SKUKILL_CACHE_PREFIX = "seckill:skus:";
    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:"; //后面跟着商品随机码

    @Override
    public void uploadSeckillSkuLatest3Days() {
        //1、数库扫描最近三天需要参加秒杀服务的活动
        R session = couponFeignService.getLatest3DaySession();
        if (session.getCode() == 0){
            //上架商品
            List<SeckillSessionsWithSkus> sessionData = session.getData(new TypeReference<List<SeckillSessionsWithSkus>>() {
            });
            //缓存到redis
            //1、缓存活动信息
            saveSessionInfos(sessionData);

            //2、缓存活动相关的商品信息
            saveSessionSkuInfos(sessionData);
        }

    }


    public List<SeckillSkuRedisTo> blockHandler(BlockException e){
        log.info("注解式阻塞，流量过大");
        return null;
    }
    /**
     * 返回当前时间可以参与的秒杀商品信息
     * */
    @SentinelResource(value = "getCurrentSeckillSkusResource",blockHandler = "blockHandler")
    //还可以写fallback = ""，所有异常都可以重写，跨类+fallbackClass，指定类，且重写类为static
    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        //1、确定当前时间属于哪个秒杀场次
        long time = new Date().getTime();


        try(Entry entry = SphU.entry("seckillSkus")){
            Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
            for (String key : keys) {
                String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
                String[] s = replace.split("_");
                Long start = Long.parseLong(s[0]);
                Long end = Long.parseLong(s[1]);
                if (time>=start && time<end){
                    //2、获取这个场次需要的所有商品信息
                    List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                    BoundHashOperations<String, String, Object> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                    List<Object> list = hashOps.multiGet(range);
                    if (list != null){
                        List<SeckillSkuRedisTo> collect = list.stream().map(item -> {
                            SeckillSkuRedisTo redisTo = JSON.parseObject((String) item, SeckillSkuRedisTo.class);
//                        redisTo.setRandomCode(null);//当前秒杀开始需要随机码
                            return redisTo;
                        }).collect(Collectors.toList());
                        return collect;
                    }
                    break;
                }
            }

        }catch (BlockException e){
            log.info("资源被限流，{}",e.getMessage());
        }



        //2、获取这个模式场次需要的所有商品信息

        return null;
    }


    /**
     * 查询当前sku是否参加秒活动
     * */
    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {

        //1、找到所有需要参加秒杀商品的key
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = hashOps.keys();
        if (keys !=null && keys.size()>0){
//            String regx = "\\d_" + skuId;
            for (String key : keys) {
//                System.out.println("结果："+skuId.toString().equals(key.split("_")[1]));
                if (skuId.toString().equals(key.split("_")[1])) {
                    String json = hashOps.get(key);
                    SeckillSkuRedisTo skuRedisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);

                    //随机码需要屏蔽
                    long currentTime = new Date().getTime();
                    Long startTime = skuRedisTo.getStartTime();
                    Long endTime = skuRedisTo.getEndTime();
                    if (currentTime>=startTime && currentTime <endTime){

                    }else {
                        skuRedisTo.setRandomCode(null);
                    }

                    return  skuRedisTo;
                }
            }
        }

        return null;
    }


    /**
     * 秒杀活动操作
     * */
    @Override
    public String kill(String killId, String key, Integer num) {

        long l1 = System.currentTimeMillis();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        //1、获取当前秒杀商品的信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);

        String json = hashOps.get(killId);
        if (StringUtils.isEmpty(json)){
            return null;
        }else {
            SeckillSkuRedisTo redisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
            //检验合法性
            Long startTime = redisTo.getStartTime();
            Long endTime = redisTo.getEndTime();
            long currentTime = new Date().getTime();
            long ttl = endTime - currentTime;
            //1、检验时间合法性
            if ( currentTime >= startTime && currentTime <= endTime ){

                //2、检验商品id和随机码是否正确
                String randomCode = redisTo.getRandomCode();
                String skuId = redisTo.getPromotionSessionId() + "_" + redisTo.getSkuId();
                if (randomCode.equals(key) && skuId.equals(killId)){
                    //3、验证购买的商品数量是否合理
                    if (num <= Integer.valueOf(redisTo.getSeckillLimit().intValue())){
                        //4、验证改账户是否买过了(幂等性处理；设置秒杀成功的占位符 userId_SessionId_skuId)
                        //setInx
                        String redisKey = memberRespVo.getId() + "_" + skuId;
                        //自动过期key
                        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if (ifAbsent){
                            //从未买过 占位成功
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);

                            //抢购成功
                            boolean b = semaphore.tryAcquire(num);
                            if (b) {
                                //5、快速下单 发送MQ消息
                                String timeId = IdWorker.getTimeId();//??
                                SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
                                seckillOrderTo.setOrderSn(timeId);
                                seckillOrderTo.setMemberId(memberRespVo.getId());
                                seckillOrderTo.setSkuId(redisTo.getSkuId());
                                seckillOrderTo.setNum(num);
                                seckillOrderTo.setSeckillPrice(redisTo.getSeckillPrice());
                                seckillOrderTo.setPromotionSessionId(redisTo.getPromotionSessionId());
                                rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", seckillOrderTo);

                                long l2 = System.currentTimeMillis();
                                log.info("时间：{}",(l2-l1));

                                return timeId;
                            }
                            return null;

                        }else {
                            //买过 占位失败
                            return null;
                        }
                    }
                }else {
                    return null;
                }
            }else {
                return null;
            }
        }

        return null;
    }


    private void saveSessionInfos( List<SeckillSessionsWithSkus> sessions){
        if (sessions != null){
            sessions.stream().forEach(session -> {
                Long startTime = session.getStartTime().getTime();
                Long endTime = session.getEndTime().getTime();
                String key = SESSIONS_CACHE_PREFIX +  startTime + "_" + endTime;
                //查看redis有没有key ，重复就不进行操作
                Boolean hasKey = redisTemplate.hasKey(key);
                //缓存活动信息
                if (!hasKey){
                    List<String> collect = session.getRelationSkus().stream().map(item ->
                            item.getPromotionSessionId()+"_"+
                                    item.getSkuId().toString()
                    ).collect(Collectors.toList());
                    redisTemplate.opsForList().leftPushAll(key,collect);
                }

            });
        }

    }


    private void saveSessionSkuInfos( List<SeckillSessionsWithSkus> sessions){

        sessions.stream().forEach(session -> {
            //准备hash操作
            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            session.getRelationSkus().stream().forEach(seckillSkuVo -> {


                if (!ops.hasKey(seckillSkuVo.getPromotionSessionId().toString()
                        +"_"+seckillSkuVo.getSkuId().toString())){
                    //缓存活动相关的商品信息
                    SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                    //1、sku的基本信息
                    R skuInfo = productFeiginService.getSkuInfo(seckillSkuVo.getSkuId());
                    if (skuInfo.getCode() == 0){
                        SkuInfoVo info = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        redisTo.setSkuInfoVo(info);
                    }

                    //2、sku秒杀信息
                    BeanUtils.copyProperties(seckillSkuVo,redisTo);

                    //3、设置当前商品的秒杀时间
                    redisTo.setStartTime(session.getStartTime().getTime());
                    redisTo.setEndTime(session.getEndTime().getTime());

                    //4、随机码 （隐藏商品的sku等信息，防止被攻击  2拿随机码到redis认证才减库存）
                    String token = UUID.randomUUID().toString().replace("-", "");

                    redisTo.setRandomCode(token);

                    String redisToString = JSON.toJSONString(redisTo);
                    ops.put(seckillSkuVo.getPromotionSessionId().toString()
                            +"_"+seckillSkuVo.getSkuId().toString(),redisToString);

                    //5、引入库存引入分布式的信号量 (限流)
                    //如果当前这个场次的商品的库存信息已经上架 就不需要上架
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    //商品的秒杀数量作为信号量
                    semaphore.trySetPermits(Integer.valueOf(seckillSkuVo.getSeckillCount().intValue()));
                }


            });
        });
    }

}
